package com.feeyo.groundservice.base_util.upgrade

import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
import androidx.core.net.toUri
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.Utils
import com.feeyo.groundservice.base_util.FyLog
import com.feeyo.groundservice.base_util.R
import com.feeyo.groundservice.base_util.getFileCachePath
import com.feeyo.groundservice.base_util.toastCenter
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.impl.LoadingPopupView
import com.lxj.xpopup.interfaces.SimpleCallback

/**
 *作者：QLH on 2020-03-20
 *描述：版本更新工具类,可以设置代理的
 */

internal class UpgradeManagerUtil(val activity: AppCompatActivity) {

    private val TAG = javaClass.simpleName

    //临时保存安装包路径
    private var installApkPath: String? = null

    private val apkInstallLauncher =
        activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode === RESULT_OK) {
                installApkPath?.let {
                    AppInstallUtil.installApkNew(activity, it)
                } ?: toastCenter("安装地址为空")
            }
        }

    private val loading = XPopup.Builder(ActivityUtils.getTopActivity())
        .dismissOnTouchOutside(false)
        .isLightNavigationBar(true)
        .dismissOnBackPressed(false)
        .hasShadowBg(false)
        .setPopupCallback(object : SimpleCallback() {
            override fun beforeShow(popupView: BasePopupView) {
                //反射出设置进度的控件
                getTitleTextView(popupView as LoadingPopupView)
            }
        })
        .asLoading("已下载", R.layout.view_pop_loading, LoadingPopupView.Style.ProgressBar)

    private var titleTv: TextView? = null

    /**
     * 后台下载
     */
    fun checkUpdate(downUrl: String) {
        getFileCachePath("${System.currentTimeMillis()}.apk")?.let { path ->
            loading.show()
            DownloadUtil.download(downUrl, path, object : DownloadUtil.DownloadListener {
                override fun onError(msg: String?) {
                    FyLog.e(TAG, "下载失败:$msg")
                    loading.dismiss()
                }

                override fun onProgress(download: Long, total: Long) {
                    val process = (download * 100 / total)
                    titleTv?.text = "已下载$process%"
                    if (download == total) {
                        loading.dismiss()
                        FyLog.e(TAG, "准备安装:$path")
                        checkAndInstall(Utils.getApp(), path)
                    }
                }
            })
        } ?: toastCenter("没有存储地址")

    }

    private fun checkAndInstall(context: Context, path: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (context.packageManager.canRequestPackageInstalls()) {
                AppInstallUtil.installApkNew(context, path)
            } else {
                FyLog.e(TAG, "未知应用，先授权，采用特殊安装方式")
                installApkPath = path
                val selfPackageUri = "package:${context.packageName}".toUri()
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, selfPackageUri)
                apkInstallLauncher.launch(intent)
            }
        } else {
            AppInstallUtil.installApkNew(context, path)
        }
    }

    private fun getTitleTextView(popupView: LoadingPopupView) {
        try {
            val field = popupView.javaClass.getDeclaredField("tv_title")
            field.isAccessible = true
            titleTv = field.get(popupView) as TextView
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}